<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Leetcode 题解 - 搜索 | Zhang Shuo'blog</title><meta name="keywords" content="Leetcode题解"><meta name="author" content="Zhang Shuo"><meta name="copyright" content="Zhang Shuo"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="Leetcode 题解 - 搜索  Leetcode 题解 - 搜索 BFS 1. 计算在网格中从原点到特定点的最短路径长度 2. 组成整数的最小平方数数量 3. 最短单词路径   DFS 1. 查找最大的连通面积 2. 矩阵中的连通分量数目 3. 好友关系的连通分量数目 4. 填充封闭区域 5. 能到达的太平洋和大西洋的区域   Backtracking 1. 数字键盘组合 2. IP 地址划分">
<meta property="og:type" content="article">
<meta property="og:title" content="Leetcode 题解 - 搜索">
<meta property="og:url" content="https://zhang-shuo-fr.gitee.io/hexo3/2021/12/06/notes/Leetcode%20%E9%A2%98%E8%A7%A3%20-%20%E6%90%9C%E7%B4%A2/index.html">
<meta property="og:site_name" content="Zhang Shuo&#39;blog">
<meta property="og:description" content="Leetcode 题解 - 搜索  Leetcode 题解 - 搜索 BFS 1. 计算在网格中从原点到特定点的最短路径长度 2. 组成整数的最小平方数数量 3. 最短单词路径   DFS 1. 查找最大的连通面积 2. 矩阵中的连通分量数目 3. 好友关系的连通分量数目 4. 填充封闭区域 5. 能到达的太平洋和大西洋的区域   Backtracking 1. 数字键盘组合 2. IP 地址划分">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://zhang-shuo-fr.gitee.io/hexo3/img/11.jpg">
<meta property="article:published_time" content="2021-12-06T09:36:00.000Z">
<meta property="article:modified_time" content="2021-12-10T12:57:38.858Z">
<meta property="article:author" content="Zhang Shuo">
<meta property="article:tag" content="Leetcode题解">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://zhang-shuo-fr.gitee.io/hexo3/img/11.jpg"><link rel="shortcut icon" href="/hexo3/img/mao_tou_xiang.jpg"><link rel="canonical" href="https://zhang-shuo-fr.gitee.io/hexo3/2021/12/06/notes/Leetcode%20%E9%A2%98%E8%A7%A3%20-%20%E6%90%9C%E7%B4%A2/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//fonts.googleapis.com" crossorigin=""/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="manifest" href="/hexo3/pwa/manifest.json"/><link rel="apple-touch-icon" sizes="180x180" href="/hexo3/pwa/apple-touch-icon.png"/><link rel="icon" type="image/png" sizes="32x32" href="/hexo3/pwa/32.png"/><link rel="icon" type="image/png" sizes="16x16" href="/hexo3/pwa/16.png"/><link rel="mask-icon" href="/hexo3/pwa/safari-pinned-tab.svg" color="#5bbad5"/><link rel="stylesheet" href="/hexo3/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Titillium+Web&amp;display=swap" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/hexo3/',
  algolia: undefined,
  localSearch: {"path":"search.xml","languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"簡"},
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: true,
    post: true
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    jQuery: 'https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js',
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/css/justifiedGallery.min.css'
    },
    fancybox: {
      js: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js',
      css: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: true,
  isanchor: true
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'Leetcode 题解 - 搜索',
  isPost: true,
  isHome: false,
  isHighlightShrink: undefined,
  isToc: true,
  postUpdate: '2021-12-10 20:57:38'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const fontSizeVal = saveToLocal.get('global-font-size')
    if (fontSizeVal !== undefined) {
      document.documentElement.style.setProperty('--global-font-size', fontSizeVal + 'px')
    }
    
    const detectApple = () => {
      if (GLOBAL_CONFIG_SITE.isHome && /iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    document.addEventListener('pjax:complete', detectApple)})(window)</script><style type="text/css">#toggle-sidebar {left:100px}</style><meta name="generator" content="Hexo 5.4.0"></head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">加载中...</div></div></div><div id="web_bg"></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src= "" data-lazy-src="/hexo3/img/mao_tou_xiang.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data"><div class="data-item is-center"><div class="data-item-link"><a href="/hexo3/archives/"><div class="headline">文章</div><div class="length-num">176</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/hexo3/tags/"><div class="headline">标签</div><div class="length-num">45</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/hexo3/categories/"><div class="headline">分类</div><div class="length-num">15</div></a></div></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/hexo3/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/hexo3/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/hexo3/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/hexo3/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fa fa-heartbeat"></i><span> 小窝</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/hexo3/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/hexo3/Gallery/"><i class="fa-fw fas fa-images"></i><span> 照片</span></a></li><li><a class="site-page child" href="/hexo3/movies/"><i class="fa-fw fas fa-video"></i><span> 电影</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/hexo3/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/hexo3/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('/hexo3/img/11.jpg')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/hexo3/">Zhang Shuo'blog</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/hexo3/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/hexo3/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/hexo3/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/hexo3/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fa fa-heartbeat"></i><span> 小窝</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/hexo3/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/hexo3/Gallery/"><i class="fa-fw fas fa-images"></i><span> 照片</span></a></li><li><a class="site-page child" href="/hexo3/movies/"><i class="fa-fw fas fa-video"></i><span> 电影</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/hexo3/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/hexo3/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">Leetcode 题解 - 搜索</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2021-12-06T09:36:00.000Z" title="发表于 2021-12-06 17:36:00">2021-12-06</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2021-12-10T12:57:38.858Z" title="更新于 2021-12-10 20:57:38">2021-12-10</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/hexo3/categories/Leetcode%E9%A2%98%E8%A7%A3/">Leetcode题解</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">6.4k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>33分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="Leetcode 题解 - 搜索"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h1 id="Leetcode-题解-搜索"><a href="#Leetcode-题解-搜索" class="headerlink" title="Leetcode 题解 - 搜索"></a>Leetcode 题解 - 搜索</h1><!-- GFM-TOC -->
<ul>
<li><a href="#leetcode-%E9%A2%98%E8%A7%A3---%E6%90%9C%E7%B4%A2">Leetcode 题解 - 搜索</a><ul>
<li><a href="#bfs">BFS</a><ul>
<li><a href="#1-%E8%AE%A1%E7%AE%97%E5%9C%A8%E7%BD%91%E6%A0%BC%E4%B8%AD%E4%BB%8E%E5%8E%9F%E7%82%B9%E5%88%B0%E7%89%B9%E5%AE%9A%E7%82%B9%E7%9A%84%E6%9C%80%E7%9F%AD%E8%B7%AF%E5%BE%84%E9%95%BF%E5%BA%A6">1. 计算在网格中从原点到特定点的最短路径长度</a></li>
<li><a href="#2-%E7%BB%84%E6%88%90%E6%95%B4%E6%95%B0%E7%9A%84%E6%9C%80%E5%B0%8F%E5%B9%B3%E6%96%B9%E6%95%B0%E6%95%B0%E9%87%8F">2. 组成整数的最小平方数数量</a></li>
<li><a href="#3-%E6%9C%80%E7%9F%AD%E5%8D%95%E8%AF%8D%E8%B7%AF%E5%BE%84">3. 最短单词路径</a></li>
</ul>
</li>
<li><a href="#dfs">DFS</a><ul>
<li><a href="#1-%E6%9F%A5%E6%89%BE%E6%9C%80%E5%A4%A7%E7%9A%84%E8%BF%9E%E9%80%9A%E9%9D%A2%E7%A7%AF">1. 查找最大的连通面积</a></li>
<li><a href="#2-%E7%9F%A9%E9%98%B5%E4%B8%AD%E7%9A%84%E8%BF%9E%E9%80%9A%E5%88%86%E9%87%8F%E6%95%B0%E7%9B%AE">2. 矩阵中的连通分量数目</a></li>
<li><a href="#3-%E5%A5%BD%E5%8F%8B%E5%85%B3%E7%B3%BB%E7%9A%84%E8%BF%9E%E9%80%9A%E5%88%86%E9%87%8F%E6%95%B0%E7%9B%AE">3. 好友关系的连通分量数目</a></li>
<li><a href="#4-%E5%A1%AB%E5%85%85%E5%B0%81%E9%97%AD%E5%8C%BA%E5%9F%9F">4. 填充封闭区域</a></li>
<li><a href="#5-%E8%83%BD%E5%88%B0%E8%BE%BE%E7%9A%84%E5%A4%AA%E5%B9%B3%E6%B4%8B%E5%92%8C%E5%A4%A7%E8%A5%BF%E6%B4%8B%E7%9A%84%E5%8C%BA%E5%9F%9F">5. 能到达的太平洋和大西洋的区域</a></li>
</ul>
</li>
<li><a href="#backtracking">Backtracking</a><ul>
<li><a href="#1-%E6%95%B0%E5%AD%97%E9%94%AE%E7%9B%98%E7%BB%84%E5%90%88">1. 数字键盘组合</a></li>
<li><a href="#2-ip-%E5%9C%B0%E5%9D%80%E5%88%92%E5%88%86">2. IP 地址划分</a></li>
<li><a href="#3-%E5%9C%A8%E7%9F%A9%E9%98%B5%E4%B8%AD%E5%AF%BB%E6%89%BE%E5%AD%97%E7%AC%A6%E4%B8%B2">3. 在矩阵中寻找字符串</a></li>
<li><a href="#4-%E8%BE%93%E5%87%BA%E4%BA%8C%E5%8F%89%E6%A0%91%E4%B8%AD%E6%89%80%E6%9C%89%E4%BB%8E%E6%A0%B9%E5%88%B0%E5%8F%B6%E5%AD%90%E7%9A%84%E8%B7%AF%E5%BE%84">4. 输出二叉树中所有从根到叶子的路径</a></li>
<li><a href="#5-%E6%8E%92%E5%88%97">5. 排列</a></li>
<li><a href="#6-%E5%90%AB%E6%9C%89%E7%9B%B8%E5%90%8C%E5%85%83%E7%B4%A0%E6%B1%82%E6%8E%92%E5%88%97">6. 含有相同元素求排列</a></li>
<li><a href="#7-%E7%BB%84%E5%90%88">7. 组合</a></li>
<li><a href="#8-%E7%BB%84%E5%90%88%E6%B1%82%E5%92%8C">8. 组合求和</a></li>
<li><a href="#9-%E5%90%AB%E6%9C%89%E7%9B%B8%E5%90%8C%E5%85%83%E7%B4%A0%E7%9A%84%E7%BB%84%E5%90%88%E6%B1%82%E5%92%8C">9. 含有相同元素的组合求和</a></li>
<li><a href="#10-1-9-%E6%95%B0%E5%AD%97%E7%9A%84%E7%BB%84%E5%90%88%E6%B1%82%E5%92%8C">10. 1-9 数字的组合求和</a></li>
<li><a href="#11-%E5%AD%90%E9%9B%86">11. 子集</a></li>
<li><a href="#12-%E5%90%AB%E6%9C%89%E7%9B%B8%E5%90%8C%E5%85%83%E7%B4%A0%E6%B1%82%E5%AD%90%E9%9B%86">12. 含有相同元素求子集</a></li>
<li><a href="#13-%E5%88%86%E5%89%B2%E5%AD%97%E7%AC%A6%E4%B8%B2%E4%BD%BF%E5%BE%97%E6%AF%8F%E4%B8%AA%E9%83%A8%E5%88%86%E9%83%BD%E6%98%AF%E5%9B%9E%E6%96%87%E6%95%B0">13. 分割字符串使得每个部分都是回文数</a></li>
<li><a href="#14-%E6%95%B0%E7%8B%AC">14. 数独</a></li>
<li><a href="#15-n-%E7%9A%87%E5%90%8E">15. N 皇后</a><!-- GFM-TOC --></li>
</ul>
</li>
</ul>
</li>
</ul>
<p>深度优先搜索和广度优先搜索广泛运用于树和图中，但是它们的应用远远不止如此。</p>
<h2 id="BFS"><a href="#BFS" class="headerlink" title="BFS"></a>BFS</h2><div align="center"> <img src= "" data-lazy-src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/95903878-725b-4ed9-bded-bc4aae0792a9.jpg"/> </div><br>

<p>广度优先搜索一层一层地进行遍历，每层遍历都是以上一层遍历的结果作为起点，遍历一个距离能访问到的所有节点。需要注意的是，遍历过的节点不能再次被遍历。</p>
<p>第一层：</p>
<ul>
<li>0 -&gt; {6,2,1,5}</li>
</ul>
<p>第二层：</p>
<ul>
<li>6 -&gt; {4}</li>
<li>2 -&gt; {}</li>
<li>1 -&gt; {}</li>
<li>5 -&gt; {3}</li>
</ul>
<p>第三层：</p>
<ul>
<li>4 -&gt; {}</li>
<li>3 -&gt; {}</li>
</ul>
<p>每一层遍历的节点都与根节点距离相同。设 d<sub>i</sub> 表示第 i 个节点与根节点的距离，推导出一个结论：对于先遍历的节点 i 与后遍历的节点 j，有 d<sub>i</sub> &lt;= d<sub>j</sub>。利用这个结论，可以求解最短路径等   <strong>最优解</strong>   问题：第一次遍历到目的节点，其所经过的路径为最短路径。应该注意的是，使用 BFS 只能求解无权图的最短路径，无权图是指从一个节点到另一个节点的代价都记为 1。</p>
<p>在程序实现 BFS 时需要考虑以下问题：</p>
<ul>
<li>队列：用来存储每一轮遍历得到的节点；</li>
<li>标记：对于遍历过的节点，应该将它标记，防止重复遍历。</li>
</ul>
<h3 id="1-计算在网格中从原点到特定点的最短路径长度"><a href="#1-计算在网格中从原点到特定点的最短路径长度" class="headerlink" title="1. 计算在网格中从原点到特定点的最短路径长度"></a>1. 计算在网格中从原点到特定点的最短路径长度</h3><p>1091. Shortest Path in Binary Matrix(Medium)</p>
<p><a target="_blank" rel="noopener" href="https://leetcode.com/problems/shortest-path-in-binary-matrix/">Leetcode</a> / <a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/shortest-path-in-binary-matrix/">力扣</a></p>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line">[[1,1,0,1],</span><br><span class="line"> [1,0,1,0],</span><br><span class="line"> [1,1,1,1],</span><br><span class="line"> [1,0,1,1]]</span><br></pre></td></tr></table></figure>

<p>题目描述：0 表示可以经过某个位置，求解从左上角到右下角的最短路径长度。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">shortestPathBinaryMatrix</span><span class="params">(<span class="keyword">int</span>[][] grids)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (grids == <span class="keyword">null</span> || grids.length == <span class="number">0</span> || grids[<span class="number">0</span>].length == <span class="number">0</span>) &#123;</span><br><span class="line">            <span class="keyword">return</span> -<span class="number">1</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">int</span>[][] direction = &#123;&#123;<span class="number">1</span>, -<span class="number">1</span>&#125;, &#123;<span class="number">1</span>, <span class="number">0</span>&#125;, &#123;<span class="number">1</span>, <span class="number">1</span>&#125;, &#123;<span class="number">0</span>, -<span class="number">1</span>&#125;, &#123;<span class="number">0</span>, <span class="number">1</span>&#125;, &#123;-<span class="number">1</span>, -<span class="number">1</span>&#125;, &#123;-<span class="number">1</span>, <span class="number">0</span>&#125;, &#123;-<span class="number">1</span>, <span class="number">1</span>&#125;&#125;;</span><br><span class="line">        <span class="keyword">int</span> m = grids.length, n = grids[<span class="number">0</span>].length;</span><br><span class="line">        Queue&lt;Pair&lt;Integer, Integer&gt;&gt; queue = <span class="keyword">new</span> LinkedList&lt;&gt;();</span><br><span class="line">        queue.add(<span class="keyword">new</span> Pair&lt;&gt;(<span class="number">0</span>, <span class="number">0</span>));</span><br><span class="line">        <span class="keyword">int</span> pathLength = <span class="number">0</span>;</span><br><span class="line">        <span class="keyword">while</span> (!queue.isEmpty()) &#123;</span><br><span class="line">            <span class="keyword">int</span> size = queue.size();</span><br><span class="line">            pathLength++;</span><br><span class="line">            <span class="keyword">while</span> (size-- &gt; <span class="number">0</span>) &#123;</span><br><span class="line">                Pair&lt;Integer, Integer&gt; cur = queue.poll();</span><br><span class="line">                <span class="keyword">int</span> cr = cur.getKey(), cc = cur.getValue();</span><br><span class="line">                <span class="keyword">if</span> (grids[cr][cc] == <span class="number">1</span>) &#123;</span><br><span class="line">                    <span class="keyword">continue</span>;</span><br><span class="line">                &#125;</span><br><span class="line">                <span class="keyword">if</span> (cr == m - <span class="number">1</span> &amp;&amp; cc == n - <span class="number">1</span>) &#123;</span><br><span class="line">                    <span class="keyword">return</span> pathLength;</span><br><span class="line">                &#125;</span><br><span class="line">                grids[cr][cc] = <span class="number">1</span>; <span class="comment">// 标记</span></span><br><span class="line">                <span class="keyword">for</span> (<span class="keyword">int</span>[] d : direction) &#123;</span><br><span class="line">                    <span class="keyword">int</span> nr = cr + d[<span class="number">0</span>], nc = cc + d[<span class="number">1</span>];</span><br><span class="line">                    <span class="keyword">if</span> (nr &lt; <span class="number">0</span> || nr &gt;= m || nc &lt; <span class="number">0</span> || nc &gt;= n) &#123;</span><br><span class="line">                        <span class="keyword">continue</span>;</span><br><span class="line">                    &#125;</span><br><span class="line">                    queue.add(<span class="keyword">new</span> Pair&lt;&gt;(nr, nc));</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> -<span class="number">1</span>;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>

<h3 id="2-组成整数的最小平方数数量"><a href="#2-组成整数的最小平方数数量" class="headerlink" title="2. 组成整数的最小平方数数量"></a>2. 组成整数的最小平方数数量</h3><p>279. Perfect Squares (Medium)</p>
<p><a target="_blank" rel="noopener" href="https://leetcode.com/problems/perfect-squares/description/">Leetcode</a> / <a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/perfect-squares/description/">力扣</a></p>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line">For example, given n = 12, return 3 because 12 = 4 + 4 + 4; given n = 13, return 2 because 13 = 4 + 9.</span><br></pre></td></tr></table></figure>

<p>可以将每个整数看成图中的一个节点，如果两个整数之差为一个平方数，那么这两个整数所在的节点就有一条边。</p>
<p>要求解最小的平方数数量，就是求解从节点 n 到节点 0 的最短路径。</p>
<p>本题也可以用动态规划求解，在之后动态规划部分中会再次出现。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">numSquares</span><span class="params">(<span class="keyword">int</span> n)</span> </span>&#123;</span><br><span class="line">    List&lt;Integer&gt; squares = generateSquares(n);</span><br><span class="line">    Queue&lt;Integer&gt; queue = <span class="keyword">new</span> LinkedList&lt;&gt;();</span><br><span class="line">    <span class="keyword">boolean</span>[] marked = <span class="keyword">new</span> <span class="keyword">boolean</span>[n + <span class="number">1</span>];</span><br><span class="line">    queue.add(n);</span><br><span class="line">    marked[n] = <span class="keyword">true</span>;</span><br><span class="line">    <span class="keyword">int</span> level = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">while</span> (!queue.isEmpty()) &#123;</span><br><span class="line">        <span class="keyword">int</span> size = queue.size();</span><br><span class="line">        level++;</span><br><span class="line">        <span class="keyword">while</span> (size-- &gt; <span class="number">0</span>) &#123;</span><br><span class="line">            <span class="keyword">int</span> cur = queue.poll();</span><br><span class="line">            <span class="keyword">for</span> (<span class="keyword">int</span> s : squares) &#123;</span><br><span class="line">                <span class="keyword">int</span> next = cur - s;</span><br><span class="line">                <span class="keyword">if</span> (next &lt; <span class="number">0</span>) &#123;</span><br><span class="line">                    <span class="keyword">break</span>;</span><br><span class="line">                &#125;</span><br><span class="line">                <span class="keyword">if</span> (next == <span class="number">0</span>) &#123;</span><br><span class="line">                    <span class="keyword">return</span> level;</span><br><span class="line">                &#125;</span><br><span class="line">                <span class="keyword">if</span> (marked[next]) &#123;</span><br><span class="line">                    <span class="keyword">continue</span>;</span><br><span class="line">                &#125;</span><br><span class="line">                marked[next] = <span class="keyword">true</span>;</span><br><span class="line">                queue.add(next);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> n;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 生成小于 n 的平方数序列</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return</span> 1,4,9,...</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">private</span> List&lt;Integer&gt; <span class="title">generateSquares</span><span class="params">(<span class="keyword">int</span> n)</span> </span>&#123;</span><br><span class="line">    List&lt;Integer&gt; squares = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">    <span class="keyword">int</span> square = <span class="number">1</span>;</span><br><span class="line">    <span class="keyword">int</span> diff = <span class="number">3</span>;</span><br><span class="line">    <span class="keyword">while</span> (square &lt;= n) &#123;</span><br><span class="line">        squares.add(square);</span><br><span class="line">        square += diff;</span><br><span class="line">        diff += <span class="number">2</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> squares;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="3-最短单词路径"><a href="#3-最短单词路径" class="headerlink" title="3. 最短单词路径"></a>3. 最短单词路径</h3><p>127. Word Ladder (Medium)</p>
<p><a target="_blank" rel="noopener" href="https://leetcode.com/problems/word-ladder/description/">Leetcode</a> / <a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/word-ladder/description/">力扣</a></p>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line">Input:</span><br><span class="line">beginWord = &quot;hit&quot;,</span><br><span class="line">endWord = &quot;cog&quot;,</span><br><span class="line">wordList = [&quot;hot&quot;,&quot;dot&quot;,&quot;dog&quot;,&quot;lot&quot;,&quot;log&quot;,&quot;cog&quot;]</span><br><span class="line"></span><br><span class="line">Output: 5</span><br><span class="line"></span><br><span class="line">Explanation: As one shortest transformation is &quot;hit&quot; -&gt; &quot;hot&quot; -&gt; &quot;dot&quot; -&gt; &quot;dog&quot; -&gt; &quot;cog&quot;,</span><br><span class="line">return its length 5.</span><br></pre></td></tr></table></figure>

<figure class="highlight html"><table><tr><td class="code"><pre><span class="line">Input:</span><br><span class="line">beginWord = &quot;hit&quot;</span><br><span class="line">endWord = &quot;cog&quot;</span><br><span class="line">wordList = [&quot;hot&quot;,&quot;dot&quot;,&quot;dog&quot;,&quot;lot&quot;,&quot;log&quot;]</span><br><span class="line"></span><br><span class="line">Output: 0</span><br><span class="line"></span><br><span class="line">Explanation: The endWord &quot;cog&quot; is not in wordList, therefore no possible transformation.</span><br></pre></td></tr></table></figure>

<p>题目描述：找出一条从 beginWord 到 endWord 的最短路径，每次移动规定为改变一个字符，并且改变之后的字符串必须在 wordList 中。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">ladderLength</span><span class="params">(String beginWord, String endWord, List&lt;String&gt; wordList)</span> </span>&#123;</span><br><span class="line">    wordList.add(beginWord);</span><br><span class="line">    <span class="keyword">int</span> N = wordList.size();</span><br><span class="line">    <span class="keyword">int</span> start = N - <span class="number">1</span>;</span><br><span class="line">    <span class="keyword">int</span> end = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">while</span> (end &lt; N &amp;&amp; !wordList.get(end).equals(endWord)) &#123;</span><br><span class="line">        end++;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> (end == N) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    List&lt;Integer&gt;[] graphic = buildGraphic(wordList);</span><br><span class="line">    <span class="keyword">return</span> getShortestPath(graphic, start, end);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">private</span> List&lt;Integer&gt;[] buildGraphic(List&lt;String&gt; wordList) &#123;</span><br><span class="line">    <span class="keyword">int</span> N = wordList.size();</span><br><span class="line">    List&lt;Integer&gt;[] graphic = <span class="keyword">new</span> List[N];</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; N; i++) &#123;</span><br><span class="line">        graphic[i] = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> j = <span class="number">0</span>; j &lt; N; j++) &#123;</span><br><span class="line">            <span class="keyword">if</span> (isConnect(wordList.get(i), wordList.get(j))) &#123;</span><br><span class="line">                graphic[i].add(j);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> graphic;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">boolean</span> <span class="title">isConnect</span><span class="params">(String s1, String s2)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">int</span> diffCnt = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; s1.length() &amp;&amp; diffCnt &lt;= <span class="number">1</span>; i++) &#123;</span><br><span class="line">        <span class="keyword">if</span> (s1.charAt(i) != s2.charAt(i)) &#123;</span><br><span class="line">            diffCnt++;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> diffCnt == <span class="number">1</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">int</span> <span class="title">getShortestPath</span><span class="params">(List&lt;Integer&gt;[] graphic, <span class="keyword">int</span> start, <span class="keyword">int</span> end)</span> </span>&#123;</span><br><span class="line">    Queue&lt;Integer&gt; queue = <span class="keyword">new</span> LinkedList&lt;&gt;();</span><br><span class="line">    <span class="keyword">boolean</span>[] marked = <span class="keyword">new</span> <span class="keyword">boolean</span>[graphic.length];</span><br><span class="line">    queue.add(start);</span><br><span class="line">    marked[start] = <span class="keyword">true</span>;</span><br><span class="line">    <span class="keyword">int</span> path = <span class="number">1</span>;</span><br><span class="line">    <span class="keyword">while</span> (!queue.isEmpty()) &#123;</span><br><span class="line">        <span class="keyword">int</span> size = queue.size();</span><br><span class="line">        path++;</span><br><span class="line">        <span class="keyword">while</span> (size-- &gt; <span class="number">0</span>) &#123;</span><br><span class="line">            <span class="keyword">int</span> cur = queue.poll();</span><br><span class="line">            <span class="keyword">for</span> (<span class="keyword">int</span> next : graphic[cur]) &#123;</span><br><span class="line">                <span class="keyword">if</span> (next == end) &#123;</span><br><span class="line">                    <span class="keyword">return</span> path;</span><br><span class="line">                &#125;</span><br><span class="line">                <span class="keyword">if</span> (marked[next]) &#123;</span><br><span class="line">                    <span class="keyword">continue</span>;</span><br><span class="line">                &#125;</span><br><span class="line">                marked[next] = <span class="keyword">true</span>;</span><br><span class="line">                queue.add(next);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="DFS"><a href="#DFS" class="headerlink" title="DFS"></a>DFS</h2><div align="center"> <img src= "" data-lazy-src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/74dc31eb-6baa-47ea-ab1c-d27a0ca35093.png"/> </div><br>

<p>广度优先搜索一层一层遍历，每一层得到的所有新节点，要用队列存储起来以备下一层遍历的时候再遍历。</p>
<p>而深度优先搜索在得到一个新节点时立即对新节点进行遍历：从节点 0 出发开始遍历，得到到新节点 6 时，立马对新节点 6 进行遍历，得到新节点 4；如此反复以这种方式遍历新节点，直到没有新节点了，此时返回。返回到根节点 0 的情况是，继续对根节点 0 进行遍历，得到新节点 2，然后继续以上步骤。</p>
<p>从一个节点出发，使用 DFS 对一个图进行遍历时，能够遍历到的节点都是从初始节点可达的，DFS 常用来求解这种   <strong>可达性</strong>   问题。</p>
<p>在程序实现 DFS 时需要考虑以下问题：</p>
<ul>
<li>栈：用栈来保存当前节点信息，当遍历新节点返回时能够继续遍历当前节点。可以使用递归栈。</li>
<li>标记：和 BFS 一样同样需要对已经遍历过的节点进行标记。</li>
</ul>
<h3 id="1-查找最大的连通面积"><a href="#1-查找最大的连通面积" class="headerlink" title="1. 查找最大的连通面积"></a>1. 查找最大的连通面积</h3><p>695. Max Area of Island (Medium)</p>
<p><a target="_blank" rel="noopener" href="https://leetcode.com/problems/max-area-of-island/description/">Leetcode</a> / <a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/max-area-of-island/description/">力扣</a></p>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line">[[0,0,1,0,0,0,0,1,0,0,0,0,0],</span><br><span class="line"> [0,0,0,0,0,0,0,1,1,1,0,0,0],</span><br><span class="line"> [0,1,1,0,1,0,0,0,0,0,0,0,0],</span><br><span class="line"> [0,1,0,0,1,1,0,0,1,0,1,0,0],</span><br><span class="line"> [0,1,0,0,1,1,0,0,1,1,1,0,0],</span><br><span class="line"> [0,0,0,0,0,0,0,0,0,0,1,0,0],</span><br><span class="line"> [0,0,0,0,0,0,0,1,1,1,0,0,0],</span><br><span class="line"> [0,0,0,0,0,0,0,1,1,0,0,0,0]]</span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">private</span> <span class="keyword">int</span> m, n;</span><br><span class="line"><span class="keyword">private</span> <span class="keyword">int</span>[][] direction = &#123;&#123;<span class="number">0</span>, <span class="number">1</span>&#125;, &#123;<span class="number">0</span>, -<span class="number">1</span>&#125;, &#123;<span class="number">1</span>, <span class="number">0</span>&#125;, &#123;-<span class="number">1</span>, <span class="number">0</span>&#125;&#125;;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">maxAreaOfIsland</span><span class="params">(<span class="keyword">int</span>[][] grid)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (grid == <span class="keyword">null</span> || grid.length == <span class="number">0</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    m = grid.length;</span><br><span class="line">    n = grid[<span class="number">0</span>].length;</span><br><span class="line">    <span class="keyword">int</span> maxArea = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; m; i++) &#123;</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> j = <span class="number">0</span>; j &lt; n; j++) &#123;</span><br><span class="line">            maxArea = Math.max(maxArea, dfs(grid, i, j));</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> maxArea;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">int</span> <span class="title">dfs</span><span class="params">(<span class="keyword">int</span>[][] grid, <span class="keyword">int</span> r, <span class="keyword">int</span> c)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (r &lt; <span class="number">0</span> || r &gt;= m || c &lt; <span class="number">0</span> || c &gt;= n || grid[r][c] == <span class="number">0</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    grid[r][c] = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">int</span> area = <span class="number">1</span>;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span>[] d : direction) &#123;</span><br><span class="line">        area += dfs(grid, r + d[<span class="number">0</span>], c + d[<span class="number">1</span>]);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> area;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="2-矩阵中的连通分量数目"><a href="#2-矩阵中的连通分量数目" class="headerlink" title="2. 矩阵中的连通分量数目"></a>2. 矩阵中的连通分量数目</h3><p>200. Number of Islands (Medium)</p>
<p><a target="_blank" rel="noopener" href="https://leetcode.com/problems/number-of-islands/description/">Leetcode</a> / <a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/number-of-islands/description/">力扣</a></p>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line">Input:</span><br><span class="line">11000</span><br><span class="line">11000</span><br><span class="line">00100</span><br><span class="line">00011</span><br><span class="line"></span><br><span class="line">Output: 3</span><br></pre></td></tr></table></figure>

<p>可以将矩阵表示看成一张有向图。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">private</span> <span class="keyword">int</span> m, n;</span><br><span class="line"><span class="keyword">private</span> <span class="keyword">int</span>[][] direction = &#123;&#123;<span class="number">0</span>, <span class="number">1</span>&#125;, &#123;<span class="number">0</span>, -<span class="number">1</span>&#125;, &#123;<span class="number">1</span>, <span class="number">0</span>&#125;, &#123;-<span class="number">1</span>, <span class="number">0</span>&#125;&#125;;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">numIslands</span><span class="params">(<span class="keyword">char</span>[][] grid)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (grid == <span class="keyword">null</span> || grid.length == <span class="number">0</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    m = grid.length;</span><br><span class="line">    n = grid[<span class="number">0</span>].length;</span><br><span class="line">    <span class="keyword">int</span> islandsNum = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; m; i++) &#123;</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> j = <span class="number">0</span>; j &lt; n; j++) &#123;</span><br><span class="line">            <span class="keyword">if</span> (grid[i][j] != <span class="string">&#x27;0&#x27;</span>) &#123;</span><br><span class="line">                dfs(grid, i, j);</span><br><span class="line">                islandsNum++;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> islandsNum;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">dfs</span><span class="params">(<span class="keyword">char</span>[][] grid, <span class="keyword">int</span> i, <span class="keyword">int</span> j)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (i &lt; <span class="number">0</span> || i &gt;= m || j &lt; <span class="number">0</span> || j &gt;= n || grid[i][j] == <span class="string">&#x27;0&#x27;</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    grid[i][j] = <span class="string">&#x27;0&#x27;</span>;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span>[] d : direction) &#123;</span><br><span class="line">        dfs(grid, i + d[<span class="number">0</span>], j + d[<span class="number">1</span>]);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="3-好友关系的连通分量数目"><a href="#3-好友关系的连通分量数目" class="headerlink" title="3. 好友关系的连通分量数目"></a>3. 好友关系的连通分量数目</h3><p>547. Friend Circles (Medium)</p>
<p><a target="_blank" rel="noopener" href="https://leetcode.com/problems/friend-circles/description/">Leetcode</a> / <a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/friend-circles/description/">力扣</a></p>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line">Input:</span><br><span class="line">[[1,1,0],</span><br><span class="line"> [1,1,0],</span><br><span class="line"> [0,0,1]]</span><br><span class="line"></span><br><span class="line">Output: 2</span><br><span class="line"></span><br><span class="line">Explanation:The 0th and 1st students are direct friends, so they are in a friend circle.</span><br><span class="line">The 2nd student himself is in a friend circle. So return 2.</span><br></pre></td></tr></table></figure>

<p>题目描述：好友关系可以看成是一个无向图，例如第 0 个人与第 1 个人是好友，那么 M[0][1] 和 M[1][0] 的值都为 1。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">private</span> <span class="keyword">int</span> n;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">findCircleNum</span><span class="params">(<span class="keyword">int</span>[][] M)</span> </span>&#123;</span><br><span class="line">    n = M.length;</span><br><span class="line">    <span class="keyword">int</span> circleNum = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">boolean</span>[] hasVisited = <span class="keyword">new</span> <span class="keyword">boolean</span>[n];</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; n; i++) &#123;</span><br><span class="line">        <span class="keyword">if</span> (!hasVisited[i]) &#123;</span><br><span class="line">            dfs(M, i, hasVisited);</span><br><span class="line">            circleNum++;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> circleNum;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">dfs</span><span class="params">(<span class="keyword">int</span>[][] M, <span class="keyword">int</span> i, <span class="keyword">boolean</span>[] hasVisited)</span> </span>&#123;</span><br><span class="line">    hasVisited[i] = <span class="keyword">true</span>;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> k = <span class="number">0</span>; k &lt; n; k++) &#123;</span><br><span class="line">        <span class="keyword">if</span> (M[i][k] == <span class="number">1</span> &amp;&amp; !hasVisited[k]) &#123;</span><br><span class="line">            dfs(M, k, hasVisited);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="4-填充封闭区域"><a href="#4-填充封闭区域" class="headerlink" title="4. 填充封闭区域"></a>4. 填充封闭区域</h3><p>130. Surrounded Regions (Medium)</p>
<p><a target="_blank" rel="noopener" href="https://leetcode.com/problems/surrounded-regions/description/">Leetcode</a> / <a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/surrounded-regions/description/">力扣</a></p>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line">For example,</span><br><span class="line">X X X X</span><br><span class="line">X O O X</span><br><span class="line">X X O X</span><br><span class="line">X O X X</span><br><span class="line"></span><br><span class="line">After running your function, the board should be:</span><br><span class="line">X X X X</span><br><span class="line">X X X X</span><br><span class="line">X X X X</span><br><span class="line">X O X X</span><br></pre></td></tr></table></figure>

<p>题目描述：使被 ‘X’ 包围的 ‘O’ 转换为 ‘X’。</p>
<p>先填充最外侧，剩下的就是里侧了。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">private</span> <span class="keyword">int</span>[][] direction = &#123;&#123;<span class="number">0</span>, <span class="number">1</span>&#125;, &#123;<span class="number">0</span>, -<span class="number">1</span>&#125;, &#123;<span class="number">1</span>, <span class="number">0</span>&#125;, &#123;-<span class="number">1</span>, <span class="number">0</span>&#125;&#125;;</span><br><span class="line"><span class="keyword">private</span> <span class="keyword">int</span> m, n;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">solve</span><span class="params">(<span class="keyword">char</span>[][] board)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (board == <span class="keyword">null</span> || board.length == <span class="number">0</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    m = board.length;</span><br><span class="line">    n = board[<span class="number">0</span>].length;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; m; i++) &#123;</span><br><span class="line">        dfs(board, i, <span class="number">0</span>);</span><br><span class="line">        dfs(board, i, n - <span class="number">1</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; n; i++) &#123;</span><br><span class="line">        dfs(board, <span class="number">0</span>, i);</span><br><span class="line">        dfs(board, m - <span class="number">1</span>, i);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; m; i++) &#123;</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> j = <span class="number">0</span>; j &lt; n; j++) &#123;</span><br><span class="line">            <span class="keyword">if</span> (board[i][j] == <span class="string">&#x27;T&#x27;</span>) &#123;</span><br><span class="line">                board[i][j] = <span class="string">&#x27;O&#x27;</span>;</span><br><span class="line">            &#125; <span class="keyword">else</span> <span class="keyword">if</span> (board[i][j] == <span class="string">&#x27;O&#x27;</span>) &#123;</span><br><span class="line">                board[i][j] = <span class="string">&#x27;X&#x27;</span>;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">dfs</span><span class="params">(<span class="keyword">char</span>[][] board, <span class="keyword">int</span> r, <span class="keyword">int</span> c)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (r &lt; <span class="number">0</span> || r &gt;= m || c &lt; <span class="number">0</span> || c &gt;= n || board[r][c] != <span class="string">&#x27;O&#x27;</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    board[r][c] = <span class="string">&#x27;T&#x27;</span>;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span>[] d : direction) &#123;</span><br><span class="line">        dfs(board, r + d[<span class="number">0</span>], c + d[<span class="number">1</span>]);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="5-能到达的太平洋和大西洋的区域"><a href="#5-能到达的太平洋和大西洋的区域" class="headerlink" title="5. 能到达的太平洋和大西洋的区域"></a>5. 能到达的太平洋和大西洋的区域</h3><p>417. Pacific Atlantic Water Flow (Medium)</p>
<p><a target="_blank" rel="noopener" href="https://leetcode.com/problems/pacific-atlantic-water-flow/description/">Leetcode</a> / <a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/pacific-atlantic-water-flow/description/">力扣</a></p>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line">Given the following 5x5 matrix:</span><br><span class="line"></span><br><span class="line">  Pacific ~   ~   ~   ~   ~</span><br><span class="line">       ~  1   2   2   3  (5) *</span><br><span class="line">       ~  3   2   3  (4) (4) *</span><br><span class="line">       ~  2   4  (5)  3   1  *</span><br><span class="line">       ~ (6) (7)  1   4   5  *</span><br><span class="line">       ~ (5)  1   1   2   4  *</span><br><span class="line">          *   *   *   *   * Atlantic</span><br><span class="line"></span><br><span class="line">Return:</span><br><span class="line">[[0, 4], [1, 3], [1, 4], [2, 2], [3, 0], [3, 1], [4, 0]] (positions with parentheses in above matrix).</span><br></pre></td></tr></table></figure>

<p>左边和上边是太平洋，右边和下边是大西洋，内部的数字代表海拔，海拔高的地方的水能够流到低的地方，求解水能够流到太平洋和大西洋的所有位置。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">private</span> <span class="keyword">int</span> m, n;</span><br><span class="line"><span class="keyword">private</span> <span class="keyword">int</span>[][] matrix;</span><br><span class="line"><span class="keyword">private</span> <span class="keyword">int</span>[][] direction = &#123;&#123;<span class="number">0</span>, <span class="number">1</span>&#125;, &#123;<span class="number">0</span>, -<span class="number">1</span>&#125;, &#123;<span class="number">1</span>, <span class="number">0</span>&#125;, &#123;-<span class="number">1</span>, <span class="number">0</span>&#125;&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> List&lt;List&lt;Integer&gt;&gt; pacificAtlantic(<span class="keyword">int</span>[][] matrix) &#123;</span><br><span class="line">    List&lt;List&lt;Integer&gt;&gt; ret = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">    <span class="keyword">if</span> (matrix == <span class="keyword">null</span> || matrix.length == <span class="number">0</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> ret;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    m = matrix.length;</span><br><span class="line">    n = matrix[<span class="number">0</span>].length;</span><br><span class="line">    <span class="keyword">this</span>.matrix = matrix;</span><br><span class="line">    <span class="keyword">boolean</span>[][] canReachP = <span class="keyword">new</span> <span class="keyword">boolean</span>[m][n];</span><br><span class="line">    <span class="keyword">boolean</span>[][] canReachA = <span class="keyword">new</span> <span class="keyword">boolean</span>[m][n];</span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; m; i++) &#123;</span><br><span class="line">        dfs(i, <span class="number">0</span>, canReachP);</span><br><span class="line">        dfs(i, n - <span class="number">1</span>, canReachA);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; n; i++) &#123;</span><br><span class="line">        dfs(<span class="number">0</span>, i, canReachP);</span><br><span class="line">        dfs(m - <span class="number">1</span>, i, canReachA);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; m; i++) &#123;</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> j = <span class="number">0</span>; j &lt; n; j++) &#123;</span><br><span class="line">            <span class="keyword">if</span> (canReachP[i][j] &amp;&amp; canReachA[i][j]) &#123;</span><br><span class="line">                ret.add(Arrays.asList(i, j));</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> ret;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">dfs</span><span class="params">(<span class="keyword">int</span> r, <span class="keyword">int</span> c, <span class="keyword">boolean</span>[][] canReach)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (canReach[r][c]) &#123;</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    canReach[r][c] = <span class="keyword">true</span>;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span>[] d : direction) &#123;</span><br><span class="line">        <span class="keyword">int</span> nextR = d[<span class="number">0</span>] + r;</span><br><span class="line">        <span class="keyword">int</span> nextC = d[<span class="number">1</span>] + c;</span><br><span class="line">        <span class="keyword">if</span> (nextR &lt; <span class="number">0</span> || nextR &gt;= m || nextC &lt; <span class="number">0</span> || nextC &gt;= n</span><br><span class="line">                || matrix[r][c] &gt; matrix[nextR][nextC]) &#123;</span><br><span class="line"></span><br><span class="line">            <span class="keyword">continue</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        dfs(nextR, nextC, canReach);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="Backtracking"><a href="#Backtracking" class="headerlink" title="Backtracking"></a>Backtracking</h2><p>Backtracking（回溯）属于 DFS。</p>
<ul>
<li>普通 DFS 主要用在   <strong>可达性问题</strong>  ，这种问题只需要执行到特点的位置然后返回即可。</li>
<li>而 Backtracking 主要用于求解   <strong>排列组合</strong>   问题，例如有 { ‘a’,’b’,’c’ } 三个字符，求解所有由这三个字符排列得到的字符串，这种问题在执行到特定的位置返回之后还会继续执行求解过程。</li>
</ul>
<p>因为 Backtracking 不是立即返回，而要继续求解，因此在程序实现时，需要注意对元素的标记问题：</p>
<ul>
<li>在访问一个新元素进入新的递归调用时，需要将新元素标记为已经访问，这样才能在继续递归调用时不用重复访问该元素；</li>
<li>但是在递归返回时，需要将元素标记为未访问，因为只需要保证在一个递归链中不同时访问一个元素，可以访问已经访问过但是不在当前递归链中的元素。</li>
</ul>
<h3 id="1-数字键盘组合"><a href="#1-数字键盘组合" class="headerlink" title="1. 数字键盘组合"></a>1. 数字键盘组合</h3><p>17. Letter Combinations of a Phone Number (Medium)</p>
<p><a target="_blank" rel="noopener" href="https://leetcode.com/problems/letter-combinations-of-a-phone-number/description/">Leetcode</a> / <a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/letter-combinations-of-a-phone-number/description/">力扣</a></p>
<div align="center"> <img src= "" data-lazy-src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/9823768c-212b-4b1a-b69a-b3f59e07b977.jpg"/> </div><br>

<figure class="highlight html"><table><tr><td class="code"><pre><span class="line">Input:Digit string &quot;23&quot;</span><br><span class="line">Output: [&quot;ad&quot;, &quot;ae&quot;, &quot;af&quot;, &quot;bd&quot;, &quot;be&quot;, &quot;bf&quot;, &quot;cd&quot;, &quot;ce&quot;, &quot;cf&quot;].</span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> String[] KEYS = &#123;<span class="string">&quot;&quot;</span>, <span class="string">&quot;&quot;</span>, <span class="string">&quot;abc&quot;</span>, <span class="string">&quot;def&quot;</span>, <span class="string">&quot;ghi&quot;</span>, <span class="string">&quot;jkl&quot;</span>, <span class="string">&quot;mno&quot;</span>, <span class="string">&quot;pqrs&quot;</span>, <span class="string">&quot;tuv&quot;</span>, <span class="string">&quot;wxyz&quot;</span>&#125;;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> List&lt;String&gt; <span class="title">letterCombinations</span><span class="params">(String digits)</span> </span>&#123;</span><br><span class="line">    List&lt;String&gt; combinations = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">    <span class="keyword">if</span> (digits == <span class="keyword">null</span> || digits.length() == <span class="number">0</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> combinations;</span><br><span class="line">    &#125;</span><br><span class="line">    doCombination(<span class="keyword">new</span> StringBuilder(), combinations, digits);</span><br><span class="line">    <span class="keyword">return</span> combinations;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">doCombination</span><span class="params">(StringBuilder prefix, List&lt;String&gt; combinations, <span class="keyword">final</span> String digits)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (prefix.length() == digits.length()) &#123;</span><br><span class="line">        combinations.add(prefix.toString());</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">int</span> curDigits = digits.charAt(prefix.length()) - <span class="string">&#x27;0&#x27;</span>;</span><br><span class="line">    String letters = KEYS[curDigits];</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">char</span> c : letters.toCharArray()) &#123;</span><br><span class="line">        prefix.append(c);                         <span class="comment">// 添加</span></span><br><span class="line">        doCombination(prefix, combinations, digits);</span><br><span class="line">        prefix.deleteCharAt(prefix.length() - <span class="number">1</span>); <span class="comment">// 删除</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="2-IP-地址划分"><a href="#2-IP-地址划分" class="headerlink" title="2. IP 地址划分"></a>2. IP 地址划分</h3><p>93. Restore IP Addresses(Medium)</p>
<p><a target="_blank" rel="noopener" href="https://leetcode.com/problems/restore-ip-addresses/description/">Leetcode</a> / <a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/restore-ip-addresses/description/">力扣</a></p>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line">Given &quot;25525511135&quot;,</span><br><span class="line">return [&quot;255.255.11.135&quot;, &quot;255.255.111.35&quot;].</span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> List&lt;String&gt; <span class="title">restoreIpAddresses</span><span class="params">(String s)</span> </span>&#123;</span><br><span class="line">    List&lt;String&gt; addresses = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">    StringBuilder tempAddress = <span class="keyword">new</span> StringBuilder();</span><br><span class="line">    doRestore(<span class="number">0</span>, tempAddress, addresses, s);</span><br><span class="line">    <span class="keyword">return</span> addresses;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">doRestore</span><span class="params">(<span class="keyword">int</span> k, StringBuilder tempAddress, List&lt;String&gt; addresses, String s)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (k == <span class="number">4</span> || s.length() == <span class="number">0</span>) &#123;</span><br><span class="line">        <span class="keyword">if</span> (k == <span class="number">4</span> &amp;&amp; s.length() == <span class="number">0</span>) &#123;</span><br><span class="line">            addresses.add(tempAddress.toString());</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; s.length() &amp;&amp; i &lt;= <span class="number">2</span>; i++) &#123;</span><br><span class="line">        <span class="keyword">if</span> (i != <span class="number">0</span> &amp;&amp; s.charAt(<span class="number">0</span>) == <span class="string">&#x27;0&#x27;</span>) &#123;</span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        String part = s.substring(<span class="number">0</span>, i + <span class="number">1</span>);</span><br><span class="line">        <span class="keyword">if</span> (Integer.valueOf(part) &lt;= <span class="number">255</span>) &#123;</span><br><span class="line">            <span class="keyword">if</span> (tempAddress.length() != <span class="number">0</span>) &#123;</span><br><span class="line">                part = <span class="string">&quot;.&quot;</span> + part;</span><br><span class="line">            &#125;</span><br><span class="line">            tempAddress.append(part);</span><br><span class="line">            doRestore(k + <span class="number">1</span>, tempAddress, addresses, s.substring(i + <span class="number">1</span>));</span><br><span class="line">            tempAddress.delete(tempAddress.length() - part.length(), tempAddress.length());</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="3-在矩阵中寻找字符串"><a href="#3-在矩阵中寻找字符串" class="headerlink" title="3. 在矩阵中寻找字符串"></a>3. 在矩阵中寻找字符串</h3><p>79. Word Search (Medium)</p>
<p><a target="_blank" rel="noopener" href="https://leetcode.com/problems/word-search/description/">Leetcode</a> / <a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/word-search/description/">力扣</a></p>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line">For example,</span><br><span class="line">Given board =</span><br><span class="line">[</span><br><span class="line">  [&#x27;A&#x27;,&#x27;B&#x27;,&#x27;C&#x27;,&#x27;E&#x27;],</span><br><span class="line">  [&#x27;S&#x27;,&#x27;F&#x27;,&#x27;C&#x27;,&#x27;S&#x27;],</span><br><span class="line">  [&#x27;A&#x27;,&#x27;D&#x27;,&#x27;E&#x27;,&#x27;E&#x27;]</span><br><span class="line">]</span><br><span class="line">word = &quot;ABCCED&quot;, -&gt; returns true,</span><br><span class="line">word = &quot;SEE&quot;, -&gt; returns true,</span><br><span class="line">word = &quot;ABCB&quot;, -&gt; returns false.</span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">static</span> <span class="keyword">int</span>[][] direction = &#123;&#123;<span class="number">1</span>, <span class="number">0</span>&#125;, &#123;-<span class="number">1</span>, <span class="number">0</span>&#125;, &#123;<span class="number">0</span>, <span class="number">1</span>&#125;, &#123;<span class="number">0</span>, -<span class="number">1</span>&#125;&#125;;</span><br><span class="line"><span class="keyword">private</span> <span class="keyword">int</span> m;</span><br><span class="line"><span class="keyword">private</span> <span class="keyword">int</span> n;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">exist</span><span class="params">(<span class="keyword">char</span>[][] board, String word)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (word == <span class="keyword">null</span> || word.length() == <span class="number">0</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> (board == <span class="keyword">null</span> || board.length == <span class="number">0</span> || board[<span class="number">0</span>].length == <span class="number">0</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    m = board.length;</span><br><span class="line">    n = board[<span class="number">0</span>].length;</span><br><span class="line">    <span class="keyword">boolean</span>[][] hasVisited = <span class="keyword">new</span> <span class="keyword">boolean</span>[m][n];</span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> r = <span class="number">0</span>; r &lt; m; r++) &#123;</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> c = <span class="number">0</span>; c &lt; n; c++) &#123;</span><br><span class="line">            <span class="keyword">if</span> (backtracking(<span class="number">0</span>, r, c, hasVisited, board, word)) &#123;</span><br><span class="line">                <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">boolean</span> <span class="title">backtracking</span><span class="params">(<span class="keyword">int</span> curLen, <span class="keyword">int</span> r, <span class="keyword">int</span> c, <span class="keyword">boolean</span>[][] visited, <span class="keyword">final</span> <span class="keyword">char</span>[][] board, <span class="keyword">final</span> String word)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (curLen == word.length()) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> (r &lt; <span class="number">0</span> || r &gt;= m || c &lt; <span class="number">0</span> || c &gt;= n</span><br><span class="line">            || board[r][c] != word.charAt(curLen) || visited[r][c]) &#123;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    visited[r][c] = <span class="keyword">true</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span>[] d : direction) &#123;</span><br><span class="line">        <span class="keyword">if</span> (backtracking(curLen + <span class="number">1</span>, r + d[<span class="number">0</span>], c + d[<span class="number">1</span>], visited, board, word)) &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    visited[r][c] = <span class="keyword">false</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="4-输出二叉树中所有从根到叶子的路径"><a href="#4-输出二叉树中所有从根到叶子的路径" class="headerlink" title="4. 输出二叉树中所有从根到叶子的路径"></a>4. 输出二叉树中所有从根到叶子的路径</h3><p>257. Binary Tree Paths (Easy)</p>
<p><a target="_blank" rel="noopener" href="https://leetcode.com/problems/binary-tree-paths/description/">Leetcode</a> / <a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/binary-tree-paths/description/">力扣</a></p>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line">  1</span><br><span class="line"> /  \</span><br><span class="line">2    3</span><br><span class="line"> \</span><br><span class="line">  5</span><br></pre></td></tr></table></figure>

<figure class="highlight html"><table><tr><td class="code"><pre><span class="line">[&quot;1-&gt;2-&gt;5&quot;, &quot;1-&gt;3&quot;]</span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> List&lt;String&gt; <span class="title">binaryTreePaths</span><span class="params">(TreeNode root)</span> </span>&#123;</span><br><span class="line">    List&lt;String&gt; paths = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">    <span class="keyword">if</span> (root == <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> paths;</span><br><span class="line">    &#125;</span><br><span class="line">    List&lt;Integer&gt; values = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">    backtracking(root, values, paths);</span><br><span class="line">    <span class="keyword">return</span> paths;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">backtracking</span><span class="params">(TreeNode node, List&lt;Integer&gt; values, List&lt;String&gt; paths)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (node == <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    values.add(node.val);</span><br><span class="line">    <span class="keyword">if</span> (isLeaf(node)) &#123;</span><br><span class="line">        paths.add(buildPath(values));</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        backtracking(node.left, values, paths);</span><br><span class="line">        backtracking(node.right, values, paths);</span><br><span class="line">    &#125;</span><br><span class="line">    values.remove(values.size() - <span class="number">1</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">boolean</span> <span class="title">isLeaf</span><span class="params">(TreeNode node)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> node.left == <span class="keyword">null</span> &amp;&amp; node.right == <span class="keyword">null</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">private</span> String <span class="title">buildPath</span><span class="params">(List&lt;Integer&gt; values)</span> </span>&#123;</span><br><span class="line">    StringBuilder str = <span class="keyword">new</span> StringBuilder();</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; values.size(); i++) &#123;</span><br><span class="line">        str.append(values.get(i));</span><br><span class="line">        <span class="keyword">if</span> (i != values.size() - <span class="number">1</span>) &#123;</span><br><span class="line">            str.append(<span class="string">&quot;-&gt;&quot;</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> str.toString();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="5-排列"><a href="#5-排列" class="headerlink" title="5. 排列"></a>5. 排列</h3><p>46. Permutations (Medium)</p>
<p><a target="_blank" rel="noopener" href="https://leetcode.com/problems/permutations/description/">Leetcode</a> / <a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/permutations/description/">力扣</a></p>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line">[1,2,3] have the following permutations:</span><br><span class="line">[</span><br><span class="line">  [1,2,3],</span><br><span class="line">  [1,3,2],</span><br><span class="line">  [2,1,3],</span><br><span class="line">  [2,3,1],</span><br><span class="line">  [3,1,2],</span><br><span class="line">  [3,2,1]</span><br><span class="line">]</span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> List&lt;List&lt;Integer&gt;&gt; permute(<span class="keyword">int</span>[] nums) &#123;</span><br><span class="line">    List&lt;List&lt;Integer&gt;&gt; permutes = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">    List&lt;Integer&gt; permuteList = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">    <span class="keyword">boolean</span>[] hasVisited = <span class="keyword">new</span> <span class="keyword">boolean</span>[nums.length];</span><br><span class="line">    backtracking(permuteList, permutes, hasVisited, nums);</span><br><span class="line">    <span class="keyword">return</span> permutes;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">backtracking</span><span class="params">(List&lt;Integer&gt; permuteList, List&lt;List&lt;Integer&gt;&gt; permutes, <span class="keyword">boolean</span>[] visited, <span class="keyword">final</span> <span class="keyword">int</span>[] nums)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (permuteList.size() == nums.length) &#123;</span><br><span class="line">        permutes.add(<span class="keyword">new</span> ArrayList&lt;&gt;(permuteList)); <span class="comment">// 重新构造一个 List</span></span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; visited.length; i++) &#123;</span><br><span class="line">        <span class="keyword">if</span> (visited[i]) &#123;</span><br><span class="line">            <span class="keyword">continue</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        visited[i] = <span class="keyword">true</span>;</span><br><span class="line">        permuteList.add(nums[i]);</span><br><span class="line">        backtracking(permuteList, permutes, visited, nums);</span><br><span class="line">        permuteList.remove(permuteList.size() - <span class="number">1</span>);</span><br><span class="line">        visited[i] = <span class="keyword">false</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="6-含有相同元素求排列"><a href="#6-含有相同元素求排列" class="headerlink" title="6. 含有相同元素求排列"></a>6. 含有相同元素求排列</h3><p>47. Permutations II (Medium)</p>
<p><a target="_blank" rel="noopener" href="https://leetcode.com/problems/permutations-ii/description/">Leetcode</a> / <a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/permutations-ii/description/">力扣</a></p>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line">[1,1,2] have the following unique permutations:</span><br><span class="line">[[1,1,2], [1,2,1], [2,1,1]]</span><br></pre></td></tr></table></figure>

<p>数组元素可能含有相同的元素，进行排列时就有可能出现重复的排列，要求重复的排列只返回一个。</p>
<p>在实现上，和 Permutations 不同的是要先排序，然后在添加一个元素时，判断这个元素是否等于前一个元素，如果等于，并且前一个元素还未访问，那么就跳过这个元素。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> List&lt;List&lt;Integer&gt;&gt; permuteUnique(<span class="keyword">int</span>[] nums) &#123;</span><br><span class="line">    List&lt;List&lt;Integer&gt;&gt; permutes = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">    List&lt;Integer&gt; permuteList = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">    Arrays.sort(nums);  <span class="comment">// 排序</span></span><br><span class="line">    <span class="keyword">boolean</span>[] hasVisited = <span class="keyword">new</span> <span class="keyword">boolean</span>[nums.length];</span><br><span class="line">    backtracking(permuteList, permutes, hasVisited, nums);</span><br><span class="line">    <span class="keyword">return</span> permutes;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">backtracking</span><span class="params">(List&lt;Integer&gt; permuteList, List&lt;List&lt;Integer&gt;&gt; permutes, <span class="keyword">boolean</span>[] visited, <span class="keyword">final</span> <span class="keyword">int</span>[] nums)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (permuteList.size() == nums.length) &#123;</span><br><span class="line">        permutes.add(<span class="keyword">new</span> ArrayList&lt;&gt;(permuteList));</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; visited.length; i++) &#123;</span><br><span class="line">        <span class="keyword">if</span> (i != <span class="number">0</span> &amp;&amp; nums[i] == nums[i - <span class="number">1</span>] &amp;&amp; !visited[i - <span class="number">1</span>]) &#123;</span><br><span class="line">            <span class="keyword">continue</span>;  <span class="comment">// 防止重复</span></span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span> (visited[i])&#123;</span><br><span class="line">            <span class="keyword">continue</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        visited[i] = <span class="keyword">true</span>;</span><br><span class="line">        permuteList.add(nums[i]);</span><br><span class="line">        backtracking(permuteList, permutes, visited, nums);</span><br><span class="line">        permuteList.remove(permuteList.size() - <span class="number">1</span>);</span><br><span class="line">        visited[i] = <span class="keyword">false</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="7-组合"><a href="#7-组合" class="headerlink" title="7. 组合"></a>7. 组合</h3><p>77. Combinations (Medium)</p>
<p><a target="_blank" rel="noopener" href="https://leetcode.com/problems/combinations/description/">Leetcode</a> / <a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/combinations/description/">力扣</a></p>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line">If n = 4 and k = 2, a solution is:</span><br><span class="line">[</span><br><span class="line">  [2,4],</span><br><span class="line">  [3,4],</span><br><span class="line">  [2,3],</span><br><span class="line">  [1,2],</span><br><span class="line">  [1,3],</span><br><span class="line">  [1,4],</span><br><span class="line">]</span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> List&lt;List&lt;Integer&gt;&gt; combine(<span class="keyword">int</span> n, <span class="keyword">int</span> k) &#123;</span><br><span class="line">    List&lt;List&lt;Integer&gt;&gt; combinations = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">    List&lt;Integer&gt; combineList = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">    backtracking(combineList, combinations, <span class="number">1</span>, k, n);</span><br><span class="line">    <span class="keyword">return</span> combinations;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">backtracking</span><span class="params">(List&lt;Integer&gt; combineList, List&lt;List&lt;Integer&gt;&gt; combinations, <span class="keyword">int</span> start, <span class="keyword">int</span> k, <span class="keyword">final</span> <span class="keyword">int</span> n)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (k == <span class="number">0</span>) &#123;</span><br><span class="line">        combinations.add(<span class="keyword">new</span> ArrayList&lt;&gt;(combineList));</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = start; i &lt;= n - k + <span class="number">1</span>; i++) &#123;  <span class="comment">// 剪枝</span></span><br><span class="line">        combineList.add(i);</span><br><span class="line">        backtracking(combineList, combinations, i + <span class="number">1</span>, k - <span class="number">1</span>, n);</span><br><span class="line">        combineList.remove(combineList.size() - <span class="number">1</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="8-组合求和"><a href="#8-组合求和" class="headerlink" title="8. 组合求和"></a>8. 组合求和</h3><p>39. Combination Sum (Medium)</p>
<p><a target="_blank" rel="noopener" href="https://leetcode.com/problems/combination-sum/description/">Leetcode</a> / <a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/combination-sum/description/">力扣</a></p>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line">given candidate set [2, 3, 6, 7] and target 7,</span><br><span class="line">A solution set is:</span><br><span class="line">[[7],[2, 2, 3]]</span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> List&lt;List&lt;Integer&gt;&gt; combinationSum(<span class="keyword">int</span>[] candidates, <span class="keyword">int</span> target) &#123;</span><br><span class="line">    List&lt;List&lt;Integer&gt;&gt; combinations = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">    backtracking(<span class="keyword">new</span> ArrayList&lt;&gt;(), combinations, <span class="number">0</span>, target, candidates);</span><br><span class="line">    <span class="keyword">return</span> combinations;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">backtracking</span><span class="params">(List&lt;Integer&gt; tempCombination, List&lt;List&lt;Integer&gt;&gt; combinations,</span></span></span><br><span class="line"><span class="params"><span class="function">                          <span class="keyword">int</span> start, <span class="keyword">int</span> target, <span class="keyword">final</span> <span class="keyword">int</span>[] candidates)</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (target == <span class="number">0</span>) &#123;</span><br><span class="line">        combinations.add(<span class="keyword">new</span> ArrayList&lt;&gt;(tempCombination));</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = start; i &lt; candidates.length; i++) &#123;</span><br><span class="line">        <span class="keyword">if</span> (candidates[i] &lt;= target) &#123;</span><br><span class="line">            tempCombination.add(candidates[i]);</span><br><span class="line">            backtracking(tempCombination, combinations, i, target - candidates[i], candidates);</span><br><span class="line">            tempCombination.remove(tempCombination.size() - <span class="number">1</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="9-含有相同元素的组合求和"><a href="#9-含有相同元素的组合求和" class="headerlink" title="9. 含有相同元素的组合求和"></a>9. 含有相同元素的组合求和</h3><p>40. Combination Sum II (Medium)</p>
<p><a target="_blank" rel="noopener" href="https://leetcode.com/problems/combination-sum-ii/description/">Leetcode</a> / <a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/combination-sum-ii/description/">力扣</a></p>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line">For example, given candidate set [10, 1, 2, 7, 6, 1, 5] and target 8,</span><br><span class="line">A solution set is:</span><br><span class="line">[</span><br><span class="line">  [1, 7],</span><br><span class="line">  [1, 2, 5],</span><br><span class="line">  [2, 6],</span><br><span class="line">  [1, 1, 6]</span><br><span class="line">]</span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> List&lt;List&lt;Integer&gt;&gt; combinationSum2(<span class="keyword">int</span>[] candidates, <span class="keyword">int</span> target) &#123;</span><br><span class="line">    List&lt;List&lt;Integer&gt;&gt; combinations = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">    Arrays.sort(candidates);</span><br><span class="line">    backtracking(<span class="keyword">new</span> ArrayList&lt;&gt;(), combinations, <span class="keyword">new</span> <span class="keyword">boolean</span>[candidates.length], <span class="number">0</span>, target, candidates);</span><br><span class="line">    <span class="keyword">return</span> combinations;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">backtracking</span><span class="params">(List&lt;Integer&gt; tempCombination, List&lt;List&lt;Integer&gt;&gt; combinations,</span></span></span><br><span class="line"><span class="params"><span class="function">                          <span class="keyword">boolean</span>[] hasVisited, <span class="keyword">int</span> start, <span class="keyword">int</span> target, <span class="keyword">final</span> <span class="keyword">int</span>[] candidates)</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (target == <span class="number">0</span>) &#123;</span><br><span class="line">        combinations.add(<span class="keyword">new</span> ArrayList&lt;&gt;(tempCombination));</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = start; i &lt; candidates.length; i++) &#123;</span><br><span class="line">        <span class="keyword">if</span> (i != <span class="number">0</span> &amp;&amp; candidates[i] == candidates[i - <span class="number">1</span>] &amp;&amp; !hasVisited[i - <span class="number">1</span>]) &#123;</span><br><span class="line">            <span class="keyword">continue</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span> (candidates[i] &lt;= target) &#123;</span><br><span class="line">            tempCombination.add(candidates[i]);</span><br><span class="line">            hasVisited[i] = <span class="keyword">true</span>;</span><br><span class="line">            backtracking(tempCombination, combinations, hasVisited, i + <span class="number">1</span>, target - candidates[i], candidates);</span><br><span class="line">            hasVisited[i] = <span class="keyword">false</span>;</span><br><span class="line">            tempCombination.remove(tempCombination.size() - <span class="number">1</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="10-1-9-数字的组合求和"><a href="#10-1-9-数字的组合求和" class="headerlink" title="10. 1-9 数字的组合求和"></a>10. 1-9 数字的组合求和</h3><p>216. Combination Sum III (Medium)</p>
<p><a target="_blank" rel="noopener" href="https://leetcode.com/problems/combination-sum-iii/description/">Leetcode</a> / <a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/combination-sum-iii/description/">力扣</a></p>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line">Input: k = 3, n = 9</span><br><span class="line"></span><br><span class="line">Output:</span><br><span class="line"></span><br><span class="line">[[1,2,6], [1,3,5], [2,3,4]]</span><br></pre></td></tr></table></figure>

<p>从 1-9 数字中选出 k 个数不重复的数，使得它们的和为 n。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> List&lt;List&lt;Integer&gt;&gt; combinationSum3(<span class="keyword">int</span> k, <span class="keyword">int</span> n) &#123;</span><br><span class="line">    List&lt;List&lt;Integer&gt;&gt; combinations = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">    List&lt;Integer&gt; path = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">    backtracking(k, n, <span class="number">1</span>, path, combinations);</span><br><span class="line">    <span class="keyword">return</span> combinations;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">backtracking</span><span class="params">(<span class="keyword">int</span> k, <span class="keyword">int</span> n, <span class="keyword">int</span> start,</span></span></span><br><span class="line"><span class="params"><span class="function">                          List&lt;Integer&gt; tempCombination, List&lt;List&lt;Integer&gt;&gt; combinations)</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (k == <span class="number">0</span> &amp;&amp; n == <span class="number">0</span>) &#123;</span><br><span class="line">        combinations.add(<span class="keyword">new</span> ArrayList&lt;&gt;(tempCombination));</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> (k == <span class="number">0</span> || n == <span class="number">0</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = start; i &lt;= <span class="number">9</span>; i++) &#123;</span><br><span class="line">        tempCombination.add(i);</span><br><span class="line">        backtracking(k - <span class="number">1</span>, n - i, i + <span class="number">1</span>, tempCombination, combinations);</span><br><span class="line">        tempCombination.remove(tempCombination.size() - <span class="number">1</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="11-子集"><a href="#11-子集" class="headerlink" title="11. 子集"></a>11. 子集</h3><p>78. Subsets (Medium)</p>
<p><a target="_blank" rel="noopener" href="https://leetcode.com/problems/subsets/description/">Leetcode</a> / <a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/subsets/description/">力扣</a></p>
<p>找出集合的所有子集，子集不能重复，[1, 2] 和 [2, 1] 这种子集算重复</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> List&lt;List&lt;Integer&gt;&gt; subsets(<span class="keyword">int</span>[] nums) &#123;</span><br><span class="line">    List&lt;List&lt;Integer&gt;&gt; subsets = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">    List&lt;Integer&gt; tempSubset = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> size = <span class="number">0</span>; size &lt;= nums.length; size++) &#123;</span><br><span class="line">        backtracking(<span class="number">0</span>, tempSubset, subsets, size, nums); <span class="comment">// 不同的子集大小</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> subsets;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">backtracking</span><span class="params">(<span class="keyword">int</span> start, List&lt;Integer&gt; tempSubset, List&lt;List&lt;Integer&gt;&gt; subsets,</span></span></span><br><span class="line"><span class="params"><span class="function">                          <span class="keyword">final</span> <span class="keyword">int</span> size, <span class="keyword">final</span> <span class="keyword">int</span>[] nums)</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (tempSubset.size() == size) &#123;</span><br><span class="line">        subsets.add(<span class="keyword">new</span> ArrayList&lt;&gt;(tempSubset));</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = start; i &lt; nums.length; i++) &#123;</span><br><span class="line">        tempSubset.add(nums[i]);</span><br><span class="line">        backtracking(i + <span class="number">1</span>, tempSubset, subsets, size, nums);</span><br><span class="line">        tempSubset.remove(tempSubset.size() - <span class="number">1</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="12-含有相同元素求子集"><a href="#12-含有相同元素求子集" class="headerlink" title="12. 含有相同元素求子集"></a>12. 含有相同元素求子集</h3><p>90. Subsets II (Medium)</p>
<p><a target="_blank" rel="noopener" href="https://leetcode.com/problems/subsets-ii/description/">Leetcode</a> / <a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/subsets-ii/description/">力扣</a></p>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line">For example,</span><br><span class="line">If nums = [1,2,2], a solution is:</span><br><span class="line"></span><br><span class="line">[</span><br><span class="line">  [2],</span><br><span class="line">  [1],</span><br><span class="line">  [1,2,2],</span><br><span class="line">  [2,2],</span><br><span class="line">  [1,2],</span><br><span class="line">  []</span><br><span class="line">]</span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> List&lt;List&lt;Integer&gt;&gt; subsetsWithDup(<span class="keyword">int</span>[] nums) &#123;</span><br><span class="line">    Arrays.sort(nums);</span><br><span class="line">    List&lt;List&lt;Integer&gt;&gt; subsets = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">    List&lt;Integer&gt; tempSubset = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">    <span class="keyword">boolean</span>[] hasVisited = <span class="keyword">new</span> <span class="keyword">boolean</span>[nums.length];</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> size = <span class="number">0</span>; size &lt;= nums.length; size++) &#123;</span><br><span class="line">        backtracking(<span class="number">0</span>, tempSubset, subsets, hasVisited, size, nums); <span class="comment">// 不同的子集大小</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> subsets;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">backtracking</span><span class="params">(<span class="keyword">int</span> start, List&lt;Integer&gt; tempSubset, List&lt;List&lt;Integer&gt;&gt; subsets, <span class="keyword">boolean</span>[] hasVisited,</span></span></span><br><span class="line"><span class="params"><span class="function">                          <span class="keyword">final</span> <span class="keyword">int</span> size, <span class="keyword">final</span> <span class="keyword">int</span>[] nums)</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (tempSubset.size() == size) &#123;</span><br><span class="line">        subsets.add(<span class="keyword">new</span> ArrayList&lt;&gt;(tempSubset));</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = start; i &lt; nums.length; i++) &#123;</span><br><span class="line">        <span class="keyword">if</span> (i != <span class="number">0</span> &amp;&amp; nums[i] == nums[i - <span class="number">1</span>] &amp;&amp; !hasVisited[i - <span class="number">1</span>]) &#123;</span><br><span class="line">            <span class="keyword">continue</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        tempSubset.add(nums[i]);</span><br><span class="line">        hasVisited[i] = <span class="keyword">true</span>;</span><br><span class="line">        backtracking(i + <span class="number">1</span>, tempSubset, subsets, hasVisited, size, nums);</span><br><span class="line">        hasVisited[i] = <span class="keyword">false</span>;</span><br><span class="line">        tempSubset.remove(tempSubset.size() - <span class="number">1</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="13-分割字符串使得每个部分都是回文数"><a href="#13-分割字符串使得每个部分都是回文数" class="headerlink" title="13. 分割字符串使得每个部分都是回文数"></a>13. 分割字符串使得每个部分都是回文数</h3><p>131. Palindrome Partitioning (Medium)</p>
<p><a target="_blank" rel="noopener" href="https://leetcode.com/problems/palindrome-partitioning/description/">Leetcode</a> / <a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/palindrome-partitioning/description/">力扣</a></p>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line">For example, given s = &quot;aab&quot;,</span><br><span class="line">Return</span><br><span class="line"></span><br><span class="line">[</span><br><span class="line">  [&quot;aa&quot;,&quot;b&quot;],</span><br><span class="line">  [&quot;a&quot;,&quot;a&quot;,&quot;b&quot;]</span><br><span class="line">]</span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> List&lt;List&lt;String&gt;&gt; partition(String s) &#123;</span><br><span class="line">    List&lt;List&lt;String&gt;&gt; partitions = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">    List&lt;String&gt; tempPartition = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">    doPartition(s, partitions, tempPartition);</span><br><span class="line">    <span class="keyword">return</span> partitions;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">doPartition</span><span class="params">(String s, List&lt;List&lt;String&gt;&gt; partitions, List&lt;String&gt; tempPartition)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (s.length() == <span class="number">0</span>) &#123;</span><br><span class="line">        partitions.add(<span class="keyword">new</span> ArrayList&lt;&gt;(tempPartition));</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; s.length(); i++) &#123;</span><br><span class="line">        <span class="keyword">if</span> (isPalindrome(s, <span class="number">0</span>, i)) &#123;</span><br><span class="line">            tempPartition.add(s.substring(<span class="number">0</span>, i + <span class="number">1</span>));</span><br><span class="line">            doPartition(s.substring(i + <span class="number">1</span>), partitions, tempPartition);</span><br><span class="line">            tempPartition.remove(tempPartition.size() - <span class="number">1</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">boolean</span> <span class="title">isPalindrome</span><span class="params">(String s, <span class="keyword">int</span> begin, <span class="keyword">int</span> end)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">while</span> (begin &lt; end) &#123;</span><br><span class="line">        <span class="keyword">if</span> (s.charAt(begin++) != s.charAt(end--)) &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="14-数独"><a href="#14-数独" class="headerlink" title="14. 数独"></a>14. 数独</h3><p>37. Sudoku Solver (Hard)</p>
<p><a target="_blank" rel="noopener" href="https://leetcode.com/problems/sudoku-solver/description/">Leetcode</a> / <a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/sudoku-solver/description/">力扣</a></p>
<div align="center"> <img src= "" data-lazy-src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/0e8fdc96-83c1-4798-9abe-45fc91d70b9d.png"/> </div><br>

<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">private</span> <span class="keyword">boolean</span>[][] rowsUsed = <span class="keyword">new</span> <span class="keyword">boolean</span>[<span class="number">9</span>][<span class="number">10</span>];</span><br><span class="line"><span class="keyword">private</span> <span class="keyword">boolean</span>[][] colsUsed = <span class="keyword">new</span> <span class="keyword">boolean</span>[<span class="number">9</span>][<span class="number">10</span>];</span><br><span class="line"><span class="keyword">private</span> <span class="keyword">boolean</span>[][] cubesUsed = <span class="keyword">new</span> <span class="keyword">boolean</span>[<span class="number">9</span>][<span class="number">10</span>];</span><br><span class="line"><span class="keyword">private</span> <span class="keyword">char</span>[][] board;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">solveSudoku</span><span class="params">(<span class="keyword">char</span>[][] board)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">this</span>.board = board;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; <span class="number">9</span>; i++)</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> j = <span class="number">0</span>; j &lt; <span class="number">9</span>; j++) &#123;</span><br><span class="line">            <span class="keyword">if</span> (board[i][j] == <span class="string">&#x27;.&#x27;</span>) &#123;</span><br><span class="line">                <span class="keyword">continue</span>;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">int</span> num = board[i][j] - <span class="string">&#x27;0&#x27;</span>;</span><br><span class="line">            rowsUsed[i][num] = <span class="keyword">true</span>;</span><br><span class="line">            colsUsed[j][num] = <span class="keyword">true</span>;</span><br><span class="line">            cubesUsed[cubeNum(i, j)][num] = <span class="keyword">true</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        backtracking(<span class="number">0</span>, <span class="number">0</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">boolean</span> <span class="title">backtracking</span><span class="params">(<span class="keyword">int</span> row, <span class="keyword">int</span> col)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">while</span> (row &lt; <span class="number">9</span> &amp;&amp; board[row][col] != <span class="string">&#x27;.&#x27;</span>) &#123;</span><br><span class="line">        row = col == <span class="number">8</span> ? row + <span class="number">1</span> : row;</span><br><span class="line">        col = col == <span class="number">8</span> ? <span class="number">0</span> : col + <span class="number">1</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> (row == <span class="number">9</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> num = <span class="number">1</span>; num &lt;= <span class="number">9</span>; num++) &#123;</span><br><span class="line">        <span class="keyword">if</span> (rowsUsed[row][num] || colsUsed[col][num] || cubesUsed[cubeNum(row, col)][num]) &#123;</span><br><span class="line">            <span class="keyword">continue</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        rowsUsed[row][num] = colsUsed[col][num] = cubesUsed[cubeNum(row, col)][num] = <span class="keyword">true</span>;</span><br><span class="line">        board[row][col] = (<span class="keyword">char</span>) (num + <span class="string">&#x27;0&#x27;</span>);</span><br><span class="line">        <span class="keyword">if</span> (backtracking(row, col)) &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        board[row][col] = <span class="string">&#x27;.&#x27;</span>;</span><br><span class="line">        rowsUsed[row][num] = colsUsed[col][num] = cubesUsed[cubeNum(row, col)][num] = <span class="keyword">false</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">int</span> <span class="title">cubeNum</span><span class="params">(<span class="keyword">int</span> i, <span class="keyword">int</span> j)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">int</span> r = i / <span class="number">3</span>;</span><br><span class="line">    <span class="keyword">int</span> c = j / <span class="number">3</span>;</span><br><span class="line">    <span class="keyword">return</span> r * <span class="number">3</span> + c;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="15-N-皇后"><a href="#15-N-皇后" class="headerlink" title="15. N 皇后"></a>15. N 皇后</h3><p>51. N-Queens (Hard)</p>
<p><a target="_blank" rel="noopener" href="https://leetcode.com/problems/n-queens/description/">Leetcode</a> / <a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/n-queens/description/">力扣</a></p>
<div align="center"> <img src= "" data-lazy-src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/067b310c-6877-40fe-9dcf-10654e737485.jpg"/> </div><br>

<p>在 n*n 的矩阵中摆放 n 个皇后，并且每个皇后不能在同一行，同一列，同一对角线上，求所有的 n 皇后的解。</p>
<p>一行一行地摆放，在确定一行中的那个皇后应该摆在哪一列时，需要用三个标记数组来确定某一列是否合法，这三个标记数组分别为：列标记数组、45 度对角线标记数组和 135 度对角线标记数组。</p>
<p>45 度对角线标记数组的长度为 2 * n - 1，通过下图可以明确 (r, c) 的位置所在的数组下标为 r + c。</p>
<div align="center"> <img src= "" data-lazy-src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/9c422923-1447-4a3b-a4e1-97e663738187.jpg" width="300px"> </div><br>


<p>135 度对角线标记数组的长度也是 2 * n - 1，(r, c) 的位置所在的数组下标为 n - 1 - (r - c)。</p>
<div align="center"> <img src= "" data-lazy-src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/7a85e285-e152-4116-b6dc-3fab27ba9437.jpg" width="300px"> </div><br>

<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">private</span> List&lt;List&lt;String&gt;&gt; solutions;</span><br><span class="line"><span class="keyword">private</span> <span class="keyword">char</span>[][] nQueens;</span><br><span class="line"><span class="keyword">private</span> <span class="keyword">boolean</span>[] colUsed;</span><br><span class="line"><span class="keyword">private</span> <span class="keyword">boolean</span>[] diagonals45Used;</span><br><span class="line"><span class="keyword">private</span> <span class="keyword">boolean</span>[] diagonals135Used;</span><br><span class="line"><span class="keyword">private</span> <span class="keyword">int</span> n;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> List&lt;List&lt;String&gt;&gt; solveNQueens(<span class="keyword">int</span> n) &#123;</span><br><span class="line">    solutions = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">    nQueens = <span class="keyword">new</span> <span class="keyword">char</span>[n][n];</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; n; i++) &#123;</span><br><span class="line">        Arrays.fill(nQueens[i], <span class="string">&#x27;.&#x27;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    colUsed = <span class="keyword">new</span> <span class="keyword">boolean</span>[n];</span><br><span class="line">    diagonals45Used = <span class="keyword">new</span> <span class="keyword">boolean</span>[<span class="number">2</span> * n - <span class="number">1</span>];</span><br><span class="line">    diagonals135Used = <span class="keyword">new</span> <span class="keyword">boolean</span>[<span class="number">2</span> * n - <span class="number">1</span>];</span><br><span class="line">    <span class="keyword">this</span>.n = n;</span><br><span class="line">    backtracking(<span class="number">0</span>);</span><br><span class="line">    <span class="keyword">return</span> solutions;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">backtracking</span><span class="params">(<span class="keyword">int</span> row)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (row == n) &#123;</span><br><span class="line">        List&lt;String&gt; list = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">char</span>[] chars : nQueens) &#123;</span><br><span class="line">            list.add(<span class="keyword">new</span> String(chars));</span><br><span class="line">        &#125;</span><br><span class="line">        solutions.add(list);</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> col = <span class="number">0</span>; col &lt; n; col++) &#123;</span><br><span class="line">        <span class="keyword">int</span> diagonals45Idx = row + col;</span><br><span class="line">        <span class="keyword">int</span> diagonals135Idx = n - <span class="number">1</span> - (row - col);</span><br><span class="line">        <span class="keyword">if</span> (colUsed[col] || diagonals45Used[diagonals45Idx] || diagonals135Used[diagonals135Idx]) &#123;</span><br><span class="line">            <span class="keyword">continue</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        nQueens[row][col] = <span class="string">&#x27;Q&#x27;</span>;</span><br><span class="line">        colUsed[col] = diagonals45Used[diagonals45Idx] = diagonals135Used[diagonals135Idx] = <span class="keyword">true</span>;</span><br><span class="line">        backtracking(row + <span class="number">1</span>);</span><br><span class="line">        colUsed[col] = diagonals45Used[diagonals45Idx] = diagonals135Used[diagonals135Idx] = <span class="keyword">false</span>;</span><br><span class="line">        nQueens[row][col] = <span class="string">&#x27;.&#x27;</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">Zhang Shuo</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://zhang-shuo-fr.gitee.io/hexo3/2021/12/06/notes/Leetcode%20%E9%A2%98%E8%A7%A3%20-%20%E6%90%9C%E7%B4%A2/">https://zhang-shuo-fr.gitee.io/hexo3/2021/12/06/notes/Leetcode%20%E9%A2%98%E8%A7%A3%20-%20%E6%90%9C%E7%B4%A2/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://zhang-shuo-fr.gitee.io/hexo3" target="_blank">Zhang Shuo'blog</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/hexo3/tags/Leetcode%E9%A2%98%E8%A7%A3/">Leetcode题解</a></div><div class="post_share"><div class="social-share" data-image="/hexo3/img/11.jpg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/social-share.js/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/social-share.js/dist/js/social-share.min.js" defer></script></div></div><div class="post-reward"><div class="reward-button button--animated"><i class="fas fa-qrcode"></i> 打赏</div><div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="/hexo3/img/wechat.jpg" target="_blank"><img class="post-qr-code-img" src= "" data-lazy-src="/hexo3/img/wechat.jpg" alt="微信"/></a><div class="post-qr-code-desc">微信</div></li><li class="reward-item"><a href="/hexo3/img/alipay.jpg" target="_blank"><img class="post-qr-code-img" src= "" data-lazy-src="/hexo3/img/alipay.jpg" alt="支付宝"/></a><div class="post-qr-code-desc">支付宝</div></li></ul></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/hexo3/2021/12/06/notes/Java%20%E5%B9%B6%E5%8F%91/"><img class="prev-cover" src= "" data-lazy-src="/hexo3/img/15.jpg" onerror="onerror=null;src='/hexo3/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">Java并发</div></div></a></div><div class="next-post pull-right"><a href="/hexo3/2021/12/06/notes/Leetcode%20%E9%A2%98%E8%A7%A3%20-%20%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%92/"><img class="next-cover" src= "" data-lazy-src="/hexo3/img/12.jpg" onerror="onerror=null;src='/hexo3/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">Leetcode 题解 - 动态规划</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/hexo3/2021/12/06/notes/Leetcode%20%E9%A2%98%E8%A7%A3%20-%20%E4%BA%8C%E5%88%86%E6%9F%A5%E6%89%BE/" title="Leetcode 题解 - 二分查找"><img class="cover" src= "" data-lazy-src="/hexo3/img/1.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-12-06</div><div class="title">Leetcode 题解 - 二分查找</div></div></a></div><div><a href="/hexo3/2021/12/06/notes/Leetcode%20%E9%A2%98%E8%A7%A3%20-%20%E4%BD%8D%E8%BF%90%E7%AE%97/" title="Leetcode 题解 - 位运算"><img class="cover" src= "" data-lazy-src="/hexo3/img/18.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-12-06</div><div class="title">Leetcode 题解 - 位运算</div></div></a></div><div><a href="/hexo3/2021/12/06/notes/Leetcode%20%E9%A2%98%E8%A7%A3%20-%20%E5%88%86%E6%B2%BB/" title="Leetcode 题解 - 分治"><img class="cover" src= "" data-lazy-src="/hexo3/img/8.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-12-06</div><div class="title">Leetcode 题解 - 分治</div></div></a></div><div><a href="/hexo3/2021/12/06/notes/Leetcode%20%E9%A2%98%E8%A7%A3%20-%20%E5%8F%8C%E6%8C%87%E9%92%88/" title="Leetcode 题解 - 双指针"><img class="cover" src= "" data-lazy-src="/hexo3/img/1.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-12-06</div><div class="title">Leetcode 题解 - 双指针</div></div></a></div><div><a href="/hexo3/2021/12/06/notes/Leetcode%20%E9%A2%98%E8%A7%A3%20-%20%E5%93%88%E5%B8%8C%E8%A1%A8/" title="Leetcode 题解 - 哈希表"><img class="cover" src= "" data-lazy-src="/hexo3/img/12.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-12-06</div><div class="title">Leetcode 题解 - 哈希表</div></div></a></div><div><a href="/hexo3/2021/12/06/notes/Leetcode%20%E9%A2%98%E8%A7%A3%20-%20%E5%9B%BE/" title="Leetcode 题解 - 图"><img class="cover" src= "" data-lazy-src="/hexo3/img/19.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-12-06</div><div class="title">Leetcode 题解 - 图</div></div></a></div></div></div></div><div class="aside-content" id="aside-content"><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#Leetcode-%E9%A2%98%E8%A7%A3-%E6%90%9C%E7%B4%A2"><span class="toc-number">1.</span> <span class="toc-text">Leetcode 题解 - 搜索</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#BFS"><span class="toc-number">1.1.</span> <span class="toc-text">BFS</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1-%E8%AE%A1%E7%AE%97%E5%9C%A8%E7%BD%91%E6%A0%BC%E4%B8%AD%E4%BB%8E%E5%8E%9F%E7%82%B9%E5%88%B0%E7%89%B9%E5%AE%9A%E7%82%B9%E7%9A%84%E6%9C%80%E7%9F%AD%E8%B7%AF%E5%BE%84%E9%95%BF%E5%BA%A6"><span class="toc-number">1.1.1.</span> <span class="toc-text">1. 计算在网格中从原点到特定点的最短路径长度</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-%E7%BB%84%E6%88%90%E6%95%B4%E6%95%B0%E7%9A%84%E6%9C%80%E5%B0%8F%E5%B9%B3%E6%96%B9%E6%95%B0%E6%95%B0%E9%87%8F"><span class="toc-number">1.1.2.</span> <span class="toc-text">2. 组成整数的最小平方数数量</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-%E6%9C%80%E7%9F%AD%E5%8D%95%E8%AF%8D%E8%B7%AF%E5%BE%84"><span class="toc-number">1.1.3.</span> <span class="toc-text">3. 最短单词路径</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#DFS"><span class="toc-number">1.2.</span> <span class="toc-text">DFS</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1-%E6%9F%A5%E6%89%BE%E6%9C%80%E5%A4%A7%E7%9A%84%E8%BF%9E%E9%80%9A%E9%9D%A2%E7%A7%AF"><span class="toc-number">1.2.1.</span> <span class="toc-text">1. 查找最大的连通面积</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-%E7%9F%A9%E9%98%B5%E4%B8%AD%E7%9A%84%E8%BF%9E%E9%80%9A%E5%88%86%E9%87%8F%E6%95%B0%E7%9B%AE"><span class="toc-number">1.2.2.</span> <span class="toc-text">2. 矩阵中的连通分量数目</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-%E5%A5%BD%E5%8F%8B%E5%85%B3%E7%B3%BB%E7%9A%84%E8%BF%9E%E9%80%9A%E5%88%86%E9%87%8F%E6%95%B0%E7%9B%AE"><span class="toc-number">1.2.3.</span> <span class="toc-text">3. 好友关系的连通分量数目</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-%E5%A1%AB%E5%85%85%E5%B0%81%E9%97%AD%E5%8C%BA%E5%9F%9F"><span class="toc-number">1.2.4.</span> <span class="toc-text">4. 填充封闭区域</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#5-%E8%83%BD%E5%88%B0%E8%BE%BE%E7%9A%84%E5%A4%AA%E5%B9%B3%E6%B4%8B%E5%92%8C%E5%A4%A7%E8%A5%BF%E6%B4%8B%E7%9A%84%E5%8C%BA%E5%9F%9F"><span class="toc-number">1.2.5.</span> <span class="toc-text">5. 能到达的太平洋和大西洋的区域</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Backtracking"><span class="toc-number">1.3.</span> <span class="toc-text">Backtracking</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1-%E6%95%B0%E5%AD%97%E9%94%AE%E7%9B%98%E7%BB%84%E5%90%88"><span class="toc-number">1.3.1.</span> <span class="toc-text">1. 数字键盘组合</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-IP-%E5%9C%B0%E5%9D%80%E5%88%92%E5%88%86"><span class="toc-number">1.3.2.</span> <span class="toc-text">2. IP 地址划分</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-%E5%9C%A8%E7%9F%A9%E9%98%B5%E4%B8%AD%E5%AF%BB%E6%89%BE%E5%AD%97%E7%AC%A6%E4%B8%B2"><span class="toc-number">1.3.3.</span> <span class="toc-text">3. 在矩阵中寻找字符串</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-%E8%BE%93%E5%87%BA%E4%BA%8C%E5%8F%89%E6%A0%91%E4%B8%AD%E6%89%80%E6%9C%89%E4%BB%8E%E6%A0%B9%E5%88%B0%E5%8F%B6%E5%AD%90%E7%9A%84%E8%B7%AF%E5%BE%84"><span class="toc-number">1.3.4.</span> <span class="toc-text">4. 输出二叉树中所有从根到叶子的路径</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#5-%E6%8E%92%E5%88%97"><span class="toc-number">1.3.5.</span> <span class="toc-text">5. 排列</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#6-%E5%90%AB%E6%9C%89%E7%9B%B8%E5%90%8C%E5%85%83%E7%B4%A0%E6%B1%82%E6%8E%92%E5%88%97"><span class="toc-number">1.3.6.</span> <span class="toc-text">6. 含有相同元素求排列</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#7-%E7%BB%84%E5%90%88"><span class="toc-number">1.3.7.</span> <span class="toc-text">7. 组合</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#8-%E7%BB%84%E5%90%88%E6%B1%82%E5%92%8C"><span class="toc-number">1.3.8.</span> <span class="toc-text">8. 组合求和</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#9-%E5%90%AB%E6%9C%89%E7%9B%B8%E5%90%8C%E5%85%83%E7%B4%A0%E7%9A%84%E7%BB%84%E5%90%88%E6%B1%82%E5%92%8C"><span class="toc-number">1.3.9.</span> <span class="toc-text">9. 含有相同元素的组合求和</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#10-1-9-%E6%95%B0%E5%AD%97%E7%9A%84%E7%BB%84%E5%90%88%E6%B1%82%E5%92%8C"><span class="toc-number">1.3.10.</span> <span class="toc-text">10. 1-9 数字的组合求和</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#11-%E5%AD%90%E9%9B%86"><span class="toc-number">1.3.11.</span> <span class="toc-text">11. 子集</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#12-%E5%90%AB%E6%9C%89%E7%9B%B8%E5%90%8C%E5%85%83%E7%B4%A0%E6%B1%82%E5%AD%90%E9%9B%86"><span class="toc-number">1.3.12.</span> <span class="toc-text">12. 含有相同元素求子集</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#13-%E5%88%86%E5%89%B2%E5%AD%97%E7%AC%A6%E4%B8%B2%E4%BD%BF%E5%BE%97%E6%AF%8F%E4%B8%AA%E9%83%A8%E5%88%86%E9%83%BD%E6%98%AF%E5%9B%9E%E6%96%87%E6%95%B0"><span class="toc-number">1.3.13.</span> <span class="toc-text">13. 分割字符串使得每个部分都是回文数</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#14-%E6%95%B0%E7%8B%AC"><span class="toc-number">1.3.14.</span> <span class="toc-text">14. 数独</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#15-N-%E7%9A%87%E5%90%8E"><span class="toc-number">1.3.15.</span> <span class="toc-text">15. N 皇后</span></a></li></ol></li></ol></li></ol></div></div></div></div></main><footer id="footer" style="background-image: url('/hexo3/img/11.jpg')"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2022 By Zhang Shuo</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div><div class="footer_custom_text">Hi, welcome to my blog!</div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="font-plus" type="button" title="放大字体"><i class="fas fa-plus"></i></button><button id="font-minus" type="button" title="缩小字体"><i class="fas fa-minus"></i></button><button id="translateLink" type="button" title="简繁转换">簡</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="local-search"><div class="search-dialog"><div class="search-dialog__title" id="local-search-title">本地搜索</div><div id="local-input-panel"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div></div><hr/><div id="local-search-results"></div><span class="search-close-button"><i class="fas fa-times"></i></span></div><div id="search-mask"></div></div><div><script src="/hexo3/js/utils.js"></script><script src="/hexo3/js/main.js"></script><script src="/hexo3/js/tw_cn.js"></script><script src="https://cdn.jsdelivr.net/npm/instant.page/instantpage.min.js" type="module"></script><script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload/dist/lazyload.iife.min.js"></script><script src="/hexo3/js/search/local-search.js"></script><script>var preloader = {
  endLoading: () => {
    document.body.style.overflow = 'auto';
    document.getElementById('loading-box').classList.add("loaded")
  },
  initLoading: () => {
    document.body.style.overflow = '';
    document.getElementById('loading-box').classList.remove("loaded")

  }
}
window.addEventListener('load',preloader.endLoading())</script><div class="js-pjax"></div><div class="aplayer no-destroy" data-id="000PeZCQ1i4XVs" data-server="tencent" data-type="artist" data-fixed="true" data-mini="true" data-listFolded="false" data-order="random" data-preload="none" data-autoplay="true" muted></div><script defer="defer" id="fluttering_ribbon" mobile="true" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/canvas-fluttering-ribbon.min.js"></script><script id="canvas_nest" defer="defer" color="0,0,255" opacity="0.7" zIndex="-1" count="99" mobile="true" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/canvas-nest.min.js"></script><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/activate-power-mode.min.js"></script><script>POWERMODE.colorful = true;
POWERMODE.shake = false;
POWERMODE.mobile = true;
document.body.addEventListener('input', POWERMODE);
</script><script id="click-heart" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/click-heart.min.js" async="async" mobile="true"></script><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.js"></script><script src="https://cdn.jsdelivr.net/gh/metowolf/MetingJS@1.2/dist/Meting.min.js"></script><script src="https://cdn.jsdelivr.net/npm/pjax/pjax.min.js"></script><script>let pjaxSelectors = [
  'title',
  '#config-diff',
  '#body-wrap',
  '#rightside-config-hide',
  '#rightside-config-show',
  '.js-pjax'
]

if (false) {
  pjaxSelectors.unshift('meta[property="og:image"]', 'meta[property="og:title"]', 'meta[property="og:url"]')
}

var pjax = new Pjax({
  elements: 'a:not([target="_blank"])',
  selectors: pjaxSelectors,
  cacheBust: false,
  analytics: false,
  scrollRestoration: false
})

document.addEventListener('pjax:send', function () {

  // removeEventListener scroll 
  window.removeEventListener('scroll', window.tocScrollFn)
  window.removeEventListener('scroll', scrollCollect)

  typeof preloader === 'object' && preloader.initLoading()
  
  if (window.aplayers) {
    for (let i = 0; i < window.aplayers.length; i++) {
      if (!window.aplayers[i].options.fixed) {
        window.aplayers[i].destroy()
      }
    }
  }

  typeof typed === 'object' && typed.destroy()

  //reset readmode
  const $bodyClassList = document.body.classList
  $bodyClassList.contains('read-mode') && $bodyClassList.remove('read-mode')

})

document.addEventListener('pjax:complete', function () {
  window.refreshFn()

  document.querySelectorAll('script[data-pjax]').forEach(item => {
    const newScript = document.createElement('script')
    const content = item.text || item.textContent || item.innerHTML || ""
    Array.from(item.attributes).forEach(attr => newScript.setAttribute(attr.name, attr.value))
    newScript.appendChild(document.createTextNode(content))
    item.parentNode.replaceChild(newScript, item)
  })

  GLOBAL_CONFIG.islazyload && window.lazyLoadInstance.update()

  typeof chatBtnFn === 'function' && chatBtnFn()
  typeof panguInit === 'function' && panguInit()

  // google analytics
  typeof gtag === 'function' && gtag('config', '', {'page_path': window.location.pathname});

  // baidu analytics
  typeof _hmt === 'object' && _hmt.push(['_trackPageview',window.location.pathname]);

  typeof loadMeting === 'function' && document.getElementsByClassName('aplayer').length && loadMeting()

  // Analytics
  if (false) {
    MtaH5.pgv()
  }

  // prismjs
  typeof Prism === 'object' && Prism.highlightAll()

  typeof preloader === 'object' && preloader.endLoading()
})

document.addEventListener('pjax:error', (e) => {
  if (e.request.status === 404) {
    pjax.loadUrl('/404.html')
  }
})</script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>